<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item style="font-weight: bolder;">账号管理</el-breadcrumb-item>
      <el-breadcrumb-item>账号列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card style="margin-top:20px ;">
      <!-- 列表 -->
      <el-table :data="tableData">
        <el-table-column label="#" type="index" width="150">
        </el-table-column>
        <el-table-column prop="username" label="账号" width="180">
        </el-table-column>
        <el-table-column prop="updatedAt" label="时间" width="250">
        </el-table-column>
        <el-table-column label="账号权限" width="200">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.limit==='超级管理员'">{{scope.row.limit}}</el-tag>
            <el-tag v-else type="success">{{scope.row.limit}}</el-tag>
            <!-- <el-switch v-model='scope.row.limit' @change="userStateChanged(scope.row)" active-text="超级管理员"
              inactive-text="普通管理员"></el-switch>-->
          </template>
        </el-table-column>
        <el-table-column label="操作" width="450">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)" :disabled="isTrue">修改</el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)" :disabled="isTrue">删除</el-button>
            <!-- 分配权限按钮 -->
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showLimit(scope.row.id)" :disabled="isTrue">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="block" style="margin-top: 10px;">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum"
          :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper"
          :total="total"></el-pagination>
      </div>

      <!-- 修改对话框 -->
      <el-dialog title="账号修改" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="账号">
            <el-input v-model="ruleForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="原密码" prop="password1">
            <el-input v-model="ruleForm.password1"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password2">
            <el-input v-model="ruleForm.password2"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserInfo()">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配权限对话框 -->
      <el-dialog title="权限修改" :visible.sync="limitVisible" width="50%" @close="limitDialogClosed">
        <el-form :model="limitForm" :rules="limitRules" ref="limitForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="账号">
            <el-input v-model="limitForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="当前账号权限">
            <el-tag v-if="limitForm.limit==='超级管理员'">{{limitForm.limit}}</el-tag>
            <el-tag v-else type="success">{{limitForm.limit}}</el-tag>
          </el-form-item>
          <el-form-item label="账号权限" prop="limit_after">
            <el-select v-model="limitForm.limit_after" placeholder="请选择管理员权限">
              <el-option label="超级管理员" value="超级管理员"></el-option>
              <el-option label="普通管理员" value="普通管理员"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <!-- 底部区 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="limitVisible = false">取 消</el-button>
          <el-button type="primary" @click="limitEdit()">确 定</el-button>
        </span>
      </el-dialog>

    </el-card>
  </div>
</template>


<style lang="scss" scoped>
</style>

<script>
  import jwtDecode from 'jwt-decode'
  export default {
    data() {
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          var param = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{6,}$/;
          if (!param.test(value)) {
            callback(new Error('密码至少1个大写字母，1个小写字母和1个数字'))
          } else {
            callback();
          }
          callback();
        }
      };
      return {
        isTrue: false,
        // 分配权限的验证规则
        limitRules: {
          // 验证权限
          limit: [{
            required: true,
            message: '请选择管理员权限',
            trigger: 'change'
          }]
        },
        // 控制分配权限对话框
        limitVisible: false,
        // 分配权限对话框的表单数据
        limitForm: {
          username: '',
          limit: '',
          limit_after: ''
        },
        // 获取用户列表的参数
        queryInfo: {
          // 关键字
          query: '',
          // 当前的页数
          pagenum: 1,
          // 当前每页显示多少条数据
          pagesize: 5
        },
        total: 0,
        // 修改账号对话框的表单数据
        ruleForm: {
          username: '',
          password1: '',
          password2: ''
        },
        // 控制修改对话框
        editDialogVisible: false,
        // 列表数据
        tableData: [],
        // 账号修改的验证规则
        rules: {
          // 验证密码是否合法
          password1: [{
              required: true,
              message: '请输入密码',
              trigger: 'blur'
            },
            {
              min: 6,
              max: 18,
              message: '密码最少6个字符，最多18个字符',
              trigger: 'blur'
            },
            {
              validator: validatePass,
              trigger: 'blur'
            }
          ],
          password2: [{
              required: true,
              message: '请输入密码',
              trigger: 'blur'
            },
            {
              min: 6,
              max: 18,
              message: '密码最少6个字符，最多18个字符',
              trigger: 'blur'
            },
            {
              validator: validatePass,
              trigger: 'blur'
            }
          ]
        }
      }
    },
    created() {
      this.getUserList()
      const tokenStr = window.sessionStorage.getItem('token')
      const decode = jwtDecode(tokenStr)
      if (decode.scope !== '超级管理员') {
        this.isTrue = true
      }
    },
    methods: {
      // 根据id删除对应的用户信息
      async removeUserById(id) {
        // 弹框提示用户是否删除
        const confirmResult = await this.$confirm(
          '此操作将永久删除该管理员, 是否继续?',
          '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).catch(err => err)
        // 如果用户确定了  返回confirm     如果用户取消了 返回cancel
        if (confirmResult !== 'confirm') {
          return this.$message.info('已取消删除！')
        }
        const u = await this.$http.delete(`ordering/users/${id}`)
        if (u.status !== 200) {
          this.$message.error('删除管理员失败！')
        }
        this.getUserList()
        this.$message.success('删除管理员成功！')
      },

      // 分配权限信息
      limitEdit() {
        this.$refs.limitForm.validate(async valid => {
          if (!valid) return
          // 可以发起添加用户的网络请求
          const u = await this.$http.put(`/ordering/users/limit/${this.limitForm.id}`, {
            username: this.limitForm.username,
            limit_after: this.limitForm.limit_after
          })
          if (u.status !== 200) {
            return this.$message.error('分配管理员权限失败！')
          }

          // 隐藏添加用户的对话框
          this.limitVisible = false
          // 重新获取管理员列表数据
          this.getUserList()
          this.$message.success('分配管理员权限成功！')
        })
      },

      // 展示分配权限的对话框
      async showLimit(id) {
        const u = await this.$http.get('/ordering/users/' + id)
        if (u.status !== 200) {
          return this.$message.error('获取用户信息失败！')
        }
        this.limitForm = u.data
        this.limitVisible = true
      },
      // 监听分配权限对话框的关闭事件
      limitDialogClosed() {
        this.$refs.limitForm.resetFields()
      },
      // 修改管理员信息
      editUserInfo() {
        this.$refs.ruleForm.validate(async valid => {
          if (!valid) return
          // 可以发起添加用户的网络请求
          const u = await this.$http.put(`/ordering/users/${this.ruleForm.id}`, {
            username: this.ruleForm.username,
            password1: this.ruleForm.password1,
            password2: this.ruleForm.password2
          })
          if (u.status !== 200) {
            return this.$message.error('修改管理员信息失败！')
          }

          // 隐藏添加用户的对话框
          this.editDialogVisible = false
          // 重新获取用户列表数据
          this.getUserList()
          this.$message.success('修改管理员信息成功！')
        })
      },
      // 获取列表数据
      async getUserList() {
        const u = await this.$http.get('/ordering/users', {
          params: this.queryInfo
        })
        if (u.status !== 200) {
          return this.$message.error('获取管理员列表失败！')
        }
        this.tableData = u.data.adminList
        this.total = u.data.total
      },
      // 监听改变每页显示多少条数据
      handleSizeChange(newSize) {
        this.queryInfo.pagesize = newSize
        this.getUserList()
      },
      // 监听改变当前页码
      handleCurrentChange(newPage) {
        this.queryInfo.pagenum = newPage
        this.getUserList()
      },
      // 监听switch开关状态的改变
      async userStateChanged(userinfo) {
        const u = await this.$http.put(
          `/ordering/users/${userinfo.id}/state/${userinfo.limit}`
        )
        if (u.status !== 200) {
          userinfo.limit = !userinfo.limit
          return this.$message.error('更新管理员权限失败！')
        }
        this.$message.success('更新管理员权限成功！')
      },
      // 展示修改的对话框
      async showEditDialog(id) {
        const u = await this.$http.get('/ordering/users/' + id)
        if (u.status !== 200) {
          return this.$message.error('获取用户信息失败！')
        }
        this.ruleForm = u.data
        this.editDialogVisible = true
      },
      // 监听修改对话框的关闭事件
      editDialogClosed() {
        this.$refs.ruleForm.resetFields()
      }
    },
    watch: {
      editDialogVisible: function(val, oldVla) {
        if (this.$refs.ruleForm !== undefined) {
          this.$refs.ruleForm.resetFields();
        }
      }
    }
  }
</script>
